package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/emps")
public class EmpController {
    @Autowired
    private EmpService empService;
    @Autowired
    private DeptService deptService;

    @GetMapping
    public Result page(EmpQueryParam param) {
        log.info("员工列表查询条件：{}", param);
        param.setPage(param.getPage() == null ? 1 : param.getPage());
        param.setPageSize(param.getPageSize() == null ? 10 : param.getPageSize());
        Page<Emp> page = new Page<>(param.getPage(), param.getPageSize());
        page.addOrder(OrderItem.desc("update_time"));
        // 创建查询条件
        // select * from emp where name ? and gender = ? and entry_date between ? and ?
        LambdaQueryWrapper<Emp> lqw = new LambdaQueryWrapper<>();
        lqw.like(param.getName() != null && !param.getName().isEmpty(), Emp::getName, param.getName())
                .eq(param.getGender() != null, Emp::getGender, param.getGender())
                .between(param.getBegin() != null && param.getEnd() != null, Emp::getEntryDate, param.getBegin(), param.getEnd());
        // 调用Service层查询分页数据
        page = empService.page(page, lqw);
        List<Emp> records = page.getRecords();
        //收集所有部门id
        Set<Integer> ids = records.stream().map(Emp::getDeptId).filter(Objects::nonNull).collect(Collectors.toSet());
        System.out.println("部门id集合：" + ids);
        // 根据部门id查询部门名称
        if (!ids.isEmpty()) {
            Map<Integer, String> names = deptService.listByIds(ids).stream().collect(Collectors.toMap(Dept::getId, Dept::getName));
            // 设置部门名称到员工对象中
            records.forEach(emp -> emp.setDeptName(names.get(emp.getDeptId())));
        }
        // 封装PageResult
        PageResult<Emp> pageResult = new PageResult<>(page.getTotal(), records);
        // 返回结果
        return Result.success(pageResult);
    }

    @PostMapping
    public Result save(@RequestBody Emp emp) {
        log.info("新增员工，员工信息：{}", emp);

        // 调用service层方法保存员工信息和员工的工作经历信息
        empService.saveEmp(emp);

        return Result.success();
    }

    @DeleteMapping
    public Result delete(@RequestParam List<Integer> ids) {
        log.info("批量删除学生，{}", ids);

        // 调用service层方法批量删除员工信息和员工工作经历信息
        empService.deleteEmpByIds(ids);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        log.info("根据ID查询员工信息，id：{}", id);
        Emp empById = empService.getEmpById(id);
        return Result.success(empById);
    }

    @PutMapping
    public Result update(@RequestBody Emp emp) {
        log.info("修改员工信息，员工信息：{}", emp);
        empService.updateEmp(emp);
        // 调用service层方法修改员工信息
        return Result.success();
    }

    @GetMapping("/list")
    public Result list() {
        log.info("查询员工列表");
        List<Emp> list = empService.list();
        // 调用service层方法查询员工列表
        return Result.success(list);
    }
}
